package cn.itcast.concurrent.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class TestThreadPool {


    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 10L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(3), new MyThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());
        executor.execute(() -> {
            log.info(Thread.currentThread().getName() + "exec...st");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info(Thread.currentThread().getName() + "exec...ed");
        });

        executor.execute(() -> {
            log.info(Thread.currentThread().getName() + "exec...st");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info(Thread.currentThread().getName() + "exec...ed");
        });




    }
}

class MyThreadFactory implements ThreadFactory {
    private AtomicInteger sequence = new AtomicInteger(0);


    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, "THREAD-pool_t_" + sequence.addAndGet(1) + ":");
    }
}
